package com.minshenglife.zanzan.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.minshenglife.commons.dal.Page;
import com.minshenglife.zanzan.dao.IntegralDao;
import com.minshenglife.zanzan.dao.TurntableResultDao;
import com.minshenglife.zanzan.dao.UserDao;
import com.minshenglife.zanzan.entity.Dept;
import com.minshenglife.zanzan.entity.Integral;
import com.minshenglife.zanzan.entity.TurntableResult;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.CalcUtils;
import com.minshenglife.zanzan.pub.Keys;
import com.minshenglife.zanzan.result.UserResult;
import com.minshenglife.zanzan.service.UserService;


/**
 * 用户信息service
 * @author huodd
 *
 */
@Component
@Transactional
public class UserServiceImpl implements UserService{
	Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	@Resource
	private UserDao userDao;
	@Resource
	private IntegralDao integralDao;
	@Resource
	private TurntableResultDao trDao;
	
	@Transactional(readOnly=true)
	@Override
	public Double getRedFlowerNum(String empId) {
		User user=userDao.getUserByUserId(empId);
		return user.getRedFlowerNum();
	}

	@Override
	@Transactional(readOnly=true)
	public Long getIntegralNum(String empId) {
		User user=userDao.getUserByUserId(empId);
		return user.getIntegralNum();
	}

	@Override
	public void updateRedFlowerNum(String empId,Double redFlowerNum) {
		User user=new User();
		user.setEmpId(empId);
		user.setRedFlowerNum(redFlowerNum);
		userDao.update(user);
	}

	@Override
	public void updageIntegralNum(String empId,Long integralNum) {
		User user=new User();
		user.setEmpId(empId);
		user.setIntegralNum(integralNum);
		userDao.update(user);
	}

	@Override
	public void updageLWCode(String empId,String LWCode) {
		User user=new User();
		user.setEmpId(empId);
		user.setWXCode(LWCode);
		userDao.update(user);
	}

	@Override
	@Transactional(readOnly=true)
	public User getUserInfo(String empId) {
		return userDao.getUserByUserId(empId);
	}

	@Override
	public void updateUserInfo(User user) {
		userDao.update(user);
	}

	@Override
	@Transactional(readOnly=true)
	public boolean isUser(String empId, String idno) {
		boolean flag = false;
		User user=new User();
		user.setEmpId(empId);
		//user.setIdNo(idno);
		List<User> list= userDao.findByExample(user);
		if(list.size() > 0){
			User user2 = list.get(0);
			if((idno.toLowerCase()).equals(user2.getIdNo().toLowerCase())){
				flag = true;
			}
		}
		return flag;
		//return list.size()>0;
	}

	@Override
	@Transactional(readOnly=true)
	public boolean isExistOfLWCode(String LWCode) {
		User user=new User();
		user.setWXCode(LWCode);
		List<User> list= userDao.findByExample(user);
		return list.size()>0;
	}

	@Override
	@Transactional(readOnly=true)
	public User getUserByWXCode(String wxCode) {
		User user=new User();
		user.setWXCode(wxCode);
		List<User> list= userDao.findByExample(user);
		if(list.size()>0)
			return list.get(0);
		else
			return null;
	}

	@Override
	@Transactional(readOnly=true)
	public List<User> getUserByUserName(String userName) {
		User user=new User();
		user.setEmp_name(userName);
		return userDao.findByExample(user);
		
	}

	@Override
	@Transactional(readOnly=true)
	public Page<User> findFlowerRankList(Map<String, Object> map, int pageNo,
			int pageSize) {
		if(map==null)
			map=new HashMap<String,Object>();
		map.put("redRank", true);
		return rankList(map, pageNo, pageSize);
	}

	@Override
	@Transactional(readOnly=true)
	public Page<User> findIntegralRankList(Map<String, Object> map, int pageNo,
			int pageSize) {
		if(map==null)
			map=new HashMap<String,Object>();
		map.put("intRank", true);
		return rankList(map, pageNo, pageSize);
	}

	private Page<User> rankList(Map<String, Object> map, int pageNo,
			int pageSize) {
		int offset = (pageNo-1) * pageSize;
        Long count =userDao.countByParams(map);
        map.put("from", offset);
        map.put("to", offset+pageSize);
        List<User> rows =userDao.findByParams(map);
        Page<User> ret = new Page<User>();
        ret.setRows(rows);
        ret.setTotalRow(count);
        ret.setTotalPage(CalcUtils.calcTotalPage(pageSize, count));
        ret.setPageSize(pageSize);
        ret.setPageNo(pageNo);
        return ret;
	}

	@Override
	@Transactional(readOnly=true)
	public Page<User> findSendFlowerRankList(Map<String, Object> map,
			int pageNo, int pageSize) {
		if(map==null)
			map=new HashMap<String,Object>();
		map.put("sendFlowerRank", true);
		return rankList(map, pageNo, pageSize);
	}

	@Override
	public void updateUserIntegralNumOfLuckDraw(String openId, int num) {
		String type=Keys.INTEGRAL_TYPE_FOUR;
		
		User user=getUserByWXCode(openId);
		user.setIntegralNum(user.getIntegralNum()+num);
		userDao.update(user);
		//更新积分流水
		integralDao.add(new Integral(type,num,user.getEmpId(),Keys.INTEGRAL_STATE_ZERO));
		
		//添加抽奖流水
		trDao.add(new TurntableResult(Keys.TURNTABLERESULT_STATE_THREE, user.getEmpId(), num, num));
	}

	@Override
	public void updateUserIntegralNumOfGame(String openId) {
		String type=Keys.INTEGRAL_TYPE_FIVE;
		int num=Keys.INTEGRAL_TYPE_FIVE_RESULTNUM;//花落谁家所得积分数
		User user=getUserByWXCode(openId);
		user.setIntegralNum(user.getIntegralNum()+num);
		userDao.update(user);
		//更新积分流水
		integralDao.add(new Integral(type,num,user.getEmpId(),Keys.INTEGRAL_STATE_ZERO));
	}

	@Override
	public void updateUserCanSendFlowerNumOfLuckDraw(String openId, int num) {
		User user=getUserByWXCode(openId);
		num=1;
		user.setCanSendNum(user.getCanSendNum()+num);
		userDao.update(user);
		//添加抽奖流水
		trDao.add(new TurntableResult(Keys.TURNTABLERESULT_STATE_ONE, user.getEmpId(), num, num));
	}
	@Override
	public void updateUserCanTuCaoNumOfLuckDraw(String openId, int num) {
		User user=getUserByWXCode(openId);
		num=1;
		user.setCanTuCaoNum(user.getCanTuCaoNum()+num);
		userDao.update(user);
		//添加抽奖流水
		trDao.add(new TurntableResult(Keys.TURNTABLERESULT_STATE_TWO, user.getEmpId(), num, num));
	}
	
	@Override
	@Transactional(readOnly=true)
	public String getUserIdByOpenId(String openId){
		String userId=userDao.findByOpenId(openId);//根据openId 获取用户Id
		return userId;
	}

	@Override
	public List<UserResult> initSearchEmpInfoList(String empId) {
		List<UserResult> list=userDao.initSearchEmpInfoList(empId);
		return list;
	} 

	@Override
	public List<UserResult> findEmpInfoList(String content) {
		List<UserResult> list=userDao.findEmpInfoList(content);
		return list;
	}

	@Override
	public void EmpUnbound(String empId) {
		log.info("start EmpUnbound");
		User user =userDao.getUserByUserId(empId);
		user.setWXCode("");
		user.setHeadImageUrl("");
		user.setUnionId("");
		userDao.empUnbound(user);
		log.info("end EmpUnbound");
	}

	@Override
	public boolean batchLeaveAndNotUnbindEmpInfo() {
		log.info("start batchLeaveAndNotUnbindEmpInfo");
		try {
			List<User> list=userDao.findEmpOfLeaveAndNotUnBindList();
			if(list.size()<=0){
				log.info("LeaveAndNotUnbindEmpInfo is null : 没有已离职且未解绑的员工");
			}else{
				log.info("LeaveAndNotUnbindEmpInfo is : "+list.size());
				for(User user :list){
					user.setWXCode("");
					user.setHeadImageUrl("");
					userDao.update(user);
				}
				log.info("batchLeaveAndNotUnbindEmpInfo is success");
				return true;
			}
		} catch (Exception e) {
			log.info("batchLeaveAndNotUnbindEmpInfo is fail : error");
			e.printStackTrace();
		}
		log.info("end batchLeaveAndNotUnbindEmpInfo");
		return false;
	}

	@Override
	public void specialCare(boolean isCare, String operator, String empId) {
		log.info("start specialCare");
		User user=userDao.getUserByUserId(operator);
		String careEmps=user.getSpecialCare();
		if(careEmps==null || "".equals(careEmps)){
			careEmps+=empId;
		}else{
			if(isCare){
				if(careEmps.indexOf(empId)==-1)
					careEmps+=","+empId;
			}else{
				if(careEmps.indexOf(empId)!=-1){
					if(careEmps.indexOf(","+empId)!=-1){
						careEmps=careEmps.replaceFirst(","+empId, "");
					}else{
						careEmps=careEmps.replaceFirst(empId, "");
					}
				}
			}
		}
		user.setSpecialCare(careEmps);
		userDao.update(user);
		log.info("end specialCare");
	}

	@Override
	public Dept getUserDept(String dept_id) {
		Map< String, Object> map = new HashMap<String, Object>();
		map.put("dept_id", dept_id);
		return userDao.findDept(map);
	}

	@Override
	@Transactional(readOnly=true)
	public User getEmpUser(String empId) {
		User user=new User();
		user.setEmpId(empId);
		List<User> list= userDao.findByExample(user);
		if(list.size() == 1){
			User user2 = list.get(0);
			return user2;
		}
		return null;
	}

}
